<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns="http://www.w3.org/1999/xhtml">
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="../../../assert/css/font.css" th:href="@{/assert/css/font.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap.min.css" th:href="@{/assert/css/bootstrap.min.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap-table.css" th:href="@{/assert/css/bootstrap-table.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap-select.min.css"
          th:href="@{/assert/css/bootstrap-select.min.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrapValidator.css"
          th:href="@{/assert/css/bootstrapValidator.css}"/>
    <link rel="stylesheet" href="../../../assert/css/toastr.min.css" th:href="@{/assert/css/toastr.min.css}"/>
    <link rel="stylesheet" href="../../../assert/css/style.css" th:href="@{/assert/css/style.css}"/>
    <link rel="stylesheet" href="../../../assert/css/index.css" th:href="@{/assert/css/index.css(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"/>
    <link rel="stylesheet" href="../../../assert/css/common.css" th:href="@{/assert/css/common.css}"/>
</head>
<body class="laydate_body">
<a id="basePath" th:href="@{/}"></a>
<div class="wrapper wrapper-content">
    <div class="ibox">
    <div class="con-title">
        <h4>属性状态字段配置--<span th:text="${name}"></span></h4>
        <input type="hidden" id="type" th:value="${type}" />
        <input type="hidden" id="name" th:value="${name}" />
    </div>
    <div class="resourceCon">
        <div class="con-operation clearfix">
            <div class="obtns clearfix">
                <button class="btn btn-default" type="button" data-toggle="modal" data-target="#statusAttModal" id="statusBtn">
                    <i class="fa fa-plus"></i>新增字段
                </button>
                <button id="editBtn" class="btn btn-default" type="button">
                    <i class="fa fa-remove"></i>修改
                </button>
                <button id="deleteBtn" class="btn btn-default" type="button">
                    <i class="fa fa-remove"></i>删除
                </button>
                <a id="backToConfig"><button class="btn btn-default" type="button">返回上级</button></a>
            </div>
        </div>
        <!--属性状态字段table-->
        <table id="statusAttTable"  style="word-break:break-all; word-wrap:break-all;"></table>
        <!-- 属性状态字段Modal -->
        <div class="modal fade" id="statusAttModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop=false>
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">属性状态字段配置</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal" role="form" id="statusAttForm">
                            <div class="form-group">
                                <label class="col-sm-4 control-label">上级类型：</label>
                                <div class="col-sm-7">
                                    <input type="hidden" class="form-control" name="type" />
                                    <input type="text" class="form-control" name="typeName" readonly />
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label"><span class="respan">*</span>状态名称：</label>
                                <div class="col-sm-7">
                                    <input type="text" class="form-control" name="name" placeholder="请输入状态名称">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label"><span class="respan">*</span>数据值：</label>
                                <div class="col-sm-7">
                                    <input type="text" class="form-control" name="value" placeholder="请输入数据值"/>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label"><span class="respan">*</span>排序：</label>
                                <div class="col-sm-7">
                                    <input type="text" class="form-control" name="orderno" placeholder="请输入排序">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label">备注:</label>
                                <div class="col-sm-7">
                                    <textarea class="form-control" name="description" placeholder="请输入内容"></textarea>
                                </div>
                            </div>
                            <button type="reset" class="btn btn-default" style="display: none" id="addResetBtn"></button>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="savebtn btn btn-primary" id="addSaveBtn">保存</button>
                        <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                    </div>
                </div>
            </div>
        </div>
        <!--修改modal -->
        <div class="modal fade" id="editStatusAttModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
             data-backdrop=false>
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">修改属性状态字段配置</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal" role="form" id="editStatusAttForm">
                            <input type="hidden" name="id" id="statusAttId"/>
                            <div class="form-group">
                                <label class="col-sm-4 control-label">上级类型：</label>
                                <div class="col-sm-7">
                                    <input type="hidden" class="form-control" name="type" th:value="${type}" />
                                    <input type="text" class="form-control" name="typeName" th:value="${name}" readonly />
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label"><span class="respan">*</span>状态名称：</label>
                                <div class="col-sm-7">
                                    <input type="text" class="form-control" name="name" placeholder="请输入状态名称">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label"><span class="respan">*</span>数据值：</label>
                                <div class="col-sm-7">
                                    <input type="text" class="form-control" name="value" placeholder="请输入数据值"/>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-4 control-label"><span class="respan">*</span>排序：</label>
                                <div class="col-sm-7">
                                    <input type="text" class="form-control" name="orderno" placeholder="请输入名称">
                                </div>
                            </div>


                            <div class="form-group">
                                <label class="col-sm-4 control-label">备注:</label>
                                <div class="col-sm-7">
                                    <textarea class="form-control" name="description" placeholder="请输入内容"></textarea>
                                </div>
                            </div>
                            <button type="reset" class="btn btn-default" style="display: none" id="editResetBtn"></button>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="savebtn btn btn-primary" id="editSaveBtn">保存</button>
                        <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                    </div>
                </div>
            </div>
        </div>
        <!--删除提示 modal -->
        <div class="modal fade" id="enshureModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
             data-backdrop=false>
            <div class="modal-dialog" role="document">
                <input type="hidden" id="deleteId" value=""/>
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">删除行</h4>
                    </div>
                    <div class="modal-body">
                        <p>确定删除吗？</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="csavebtn btn btn-primary">确定</button>
                        <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
<script src="../../../assert/js/jquery.js" th:src="@{/assert/js/jquery.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/bootstrap.min.js" th:src="@{/assert/js/bootstrap.min.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/bootstrap-table.js" th:src="@{/assert/js/bootstrap-table.js}"></script>
<script src="../../../assert/js/bootstrap-select.js" th:src="@{/assert/js/bootstrap-select.js}"></script>
<script src="../../../assert/js/bootstrapValidator.js" th:src="@{/assert/js/bootstrapValidator.js}"></script>
<script src="../../../assert/js/base.js" th:src="@{/assert/js/base.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/toastr.min.js" th:src="@{/assert/js/toastr.min.js}"></script>
<script type="text/javascript">
    //项目名称
    var basePath = $("#basePath").attr("href");
    var TableInit = function () {
        var oTableInit = new Object();
        //初始化Table
        oTableInit.Init = function () {
            $('#statusAttTable').bootstrapTable({
                url: basePath + "rest/statusAtt/statusAttByPage", //请求后台的URL（*）
                method: "post", //请求方式（*）
                dataType: "json",
                contentType: "application/x-www-form-urlencoded;charset=UTF-8",
                dataField: "rows", //服务端返回数据键值 就是说记录放的键值是rows，分页时使用总记录数的键值为total
                totalField: "total",
                striped: true, //是否显示行间隔色
                cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true, //是否显示分页（*）
                sortable: true, //是否启用排序
                sortName: "id", //排序方式
                sortOrder: "desc", //排序方式
                clickToSelect: true,
                queryParams: oTableInit.queryParams, //传递参数（*）
                queryParamsType: "", //  queryParamsType = 'limit' 参数: limit, offset, search, sort, order;
                sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1, //初始化加载第一页，默认第一页
                pageSize: 10, //每页的记录行数（*）
                pageList: [10, 15, 20, 25], //可供选择的每页的行数（*）
                idField: "id",
                uniqueId: "id", //每一行的唯一标识，一般为主键列
                columns: [{
                    field: 'checkStatus',
                    title: '全选',
                    checkbox: true
                }, {
                    field: 'id',
                    title: 'ID',
                    sortable: true,
                    visible: false
                },
                    {
                        field: 'name',
                        title: '状态名称',
                        sortable: true
                    },
                    {
                        field: 'value',
                        title: '数据值',
                        sortable: true
                    },
                    {
                        field: 'orderno',
                        title: '排序',
                        sortable: true
                    },
                    {
                        field: 'lastupdatetime',
                        title: '更新时间',
                        sortable: true,
                        formatter: function (value, row, index) {
                            if (value != null) {
                                // 把时间戳修改为yyyy-mm-dd HH:mm:ss格式
                                var date = new Date(value);
                                var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
                                var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
                                var hour = date.getHours();
                                var minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                                var second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
                                return date.getFullYear() + "-" + month + "-" + currentDate + " " + hour + ":" + minute + ":" + second;
                            }
                        }
                    },
                    {
                        field: 'description',
                        title: '备注',
                        sortable: true
                    }
                ],
                formatLoadingMessage: function () {
                    return "请稍等，正在加载中...";
                },
                formatNoMatches: function () { //没有匹配的结果
                    return '无符合条件的记录';
                },
                onLoadError: function (data) {
                    $('#statusAttTable').bootstrapTable('removeAll');
                },
                responseHandler: function (res) {
                    return {
                        total: res.totalCount,
                        rows: res.result
                    };
                }
            });
        };

        //得到查询的参数
        oTableInit.queryParams = function (params) {
            var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                "pageSize": params.pageSize,
                "pageNum": params.pageNumber,
                "sortName": this.sortName,
                "sortOrder": this.sortOrder,
                "type": $.trim($("#type").val())
            };
            return temp;
        };
        return oTableInit;
    };

    // 添加属性配置字段
    var statusAttAddFun = {
        init: function () {
            statusAttAddFun.formInit();
            statusAttAddFun.save();
        },
        formInit: function () {
            // 在新增模态框显示出来前 初始化表单值
            $("#statusAttModal").on("show.bs.modal", function () {
                // 设置表单默认值
                $("#addResetBtn").click();
                $("#statusAttForm input[name='type']").val($("#type").val());
                $("#statusAttForm input[name='typeName']").val($("#name").val());
            });
        },
        save: function () {
            // 新增资源保存按钮点击事件绑定
            $("#addSaveBtn").off("click").on("click", function () {
                var bv = $('#statusAttForm').data('bootstrapValidator');
                bv.validate();
                if (bv.isValid()) {
                    //发送ajax请求
                    $.ajax({
                        type: "post",
                        url: basePath + "rest/statusAtt/statusAttAdd",
                        data: $("#statusAttModal form").serialize(),
                        success: function (data) {
                            if (data.type == "success") {
                                $("#statusAttModal").modal("hide");
                                // 提示新增成功
                                toastr.success("属性状态配置字段新增成功");
                                $("#statusAttTable").bootstrapTable("refresh");
                            } else {
                                // 提示新增失败
                                toastr.error("属性状态配置字段新增失败");
                            }
                        }
                    });
                }
            });
        }
    };

    // 修改资源
    var statusAttEditFun = {
        init: function () {
            statusAttEditFun.openEditModal();
            statusAttEditFun.formInit();
            statusAttEditFun.save();
        },
        openEditModal: function () {
            $("#editBtn").off("click").on("click", function () {
                var rows = $("#statusAttTable").bootstrapTable("getSelections");
                if (rows.length == 0) {
                    toastr.error('请选择行');
                } else if(rows.length > 1) {
                    toastr.error('单次只能选择一行进行修改');
                }else{
                    var id = rows[0].id;
                    $("#statusAttId").val(id);
                    $("#editStatusAttModal").modal("show");
                }
            });
        },
        formInit: function () {
            // 在修改模态框显示出来前 初始化表单值
            $("#editStatusAttModal").on("show.bs.modal", function () {
                var id = $("#statusAttId").val();
                $.ajax({
                    type: "post",
                    async: false,
                    url: basePath + "rest/statusAtt/statusAttGetByPK",
                    data: {id: id},
                    success: function (data) {
                        if (data != null) {
                            // 文本框值初始化
                            $("#editStatusAttModal input[name='value']").val(data.value).attr("oldvalue", data.value);
                            $("#editStatusAttModal input[name='name']").val(data.name).attr("oldvalue", data.name);
                            $("#editStatusAttModal input[name='type']").val(data.type);
                            $("#editStatusAttModal input[name='typeName']").val($("#name").val());
                            $("#editStatusAttModal input[name='orderno']").val(data.orderno);
                            $("#editStatusAttModal :input[name='description']").val(data.description);
                        }
                    }
                });
            });
        },
        save: function () {
            // 修改资源保存按钮点击事件绑定
            $("#editSaveBtn").off("click").on("click", function () {
                var bv = $('#editStatusAttForm').data('bootstrapValidator');
                bv.validate();
                if (bv.isValid()) {
                    $.ajax({
                        type: "post",
                        url: basePath + "rest/statusAtt/statusAttUpdate",
                        data: $("#editStatusAttModal form").serialize(),
                        success: function (data) {
                            if (data.type == "success") {
                                $("#editStatusAttModal").modal("hide");
                                // 提示修改成功
                                toastr.success("属性状态配置修改成功");
                                $("#statusAttTable").bootstrapTable("refresh");
                            } else {
                                // 提示修改失败
                                toastr.error("属性状态配置修改失败");
                            }
                        }
                    });
                }
            });
        }
    };

    // 删除资源
    var statusAttDeleteFun = {
        init: function () {
            statusAttDeleteFun.single();
            statusAttDeleteFun.confimDelete();
        },
        single: function () {
            //删除单行
            $("#deleteBtn").off("click").on("click", function () {
                var rows = $("#statusAttTable").bootstrapTable("getSelections");
                if (rows.length == 0) {
                    toastr.error('请选择行');
                } else if(rows.length > 1) {
                    toastr.error('单次只能选择一行进行删除');
                }else{
                    // 获取当前要删除的资源id
                    var id = rows[0].id;
                    $("#deleteId").val(id);
                    // 弹出删除确认模态框
                    $("#enshureModal").modal("show");
                }
            });
        },
        confimDelete: function () {
            // 在删除模态框中点击确定时触发的删除事件绑定
            $(".csavebtn").off("click").on("click", function () {
                var id = $("#deleteId").val();
                $.ajax({
                    type: "post",
                    url: basePath + "rest/statusAtt/statusAttDelete",
                    data: {id: id},
                    success: function (data) {
                        // 相应后关闭model框
                        $("#enshureModal").modal("hide");
                        if (data.type == "success") {
                            toastr.success('删除成功');
                        } else {
                            toastr.error('删除失败');
                        }
                        // 刷新表格
                        $("#statusAttTable").bootstrapTable("refresh");
                    }
                });
            });
        }
    };
    //添加相关
    var validateFun = {
        init: function () {
            this.initKeyValidator();
            this.initOpen();
        },
        initKeyValidator: function () {
            var option = {
                live: "enabled",
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    name: {
                        validators: {
                            notEmpty: {
                                message: '状态名称不能为空'
                            },
                            callback: {
                                message: '该名称已存在',
                                callback:function(value, validator, $field){
                                    if(value == $field.attr("oldvalue")){
                                        return true;
                                    }
                                    var isExist = false;
                                    $.ajax({
                                        type: "post",
                                        async: false,
                                        url: basePath + "rest/statusAtt/attNameUniqueCheck",
                                        data: {name: value, type: $("#type").val()},
                                        success: function (data) {
                                            if(data.type=="success"){
                                                isExist = true;
                                            }
                                        }
                                    });
                                    return isExist;
                                }
                            }
                        }
                    },
                    value: {
                        validators: {
                            notEmpty: {
                                message: '数据值不能为空'
                            },
                            callback: {
                                message: '该值已存在',
                                callback:function(value, validator, $field){
                                    if(value == $field.attr("oldvalue")){
                                        return true;
                                    }
                                    var isExist = false;
                                    $.ajax({
                                        type: "post",
                                        async: false,
                                        url: basePath + "rest/statusAtt/attValueUniqueCheck",
                                        data: {value: value, type: $("#type").val()},
                                        success: function (data) {
                                            if(data.type=="success"){
                                                isExist = true;
                                            }
                                        }
                                    });
                                    return isExist;
                                }
                            }
                        }
                    },
                    orderno: {
                        validators: {
                            notEmpty: {
                                message: '排序不能为空'
                            },
                            regexp: {
                                regexp : /^\d*$/,
                                message: '请输入整数数值'
                            }
                        }
                    }
                }
            };
            $("#statusAttForm").bootstrapValidator(option);
            $("#editStatusAttForm").bootstrapValidator(option);
        },
        initOpen: function () {
            $("#statusAttModal").on("hide.bs.modal", function () {
                $('#statusAttForm').data('bootstrapValidator').resetForm(true);
            });

            $("#editStatusAttModal").on("hide.bs.modal", function () {
                $('#editStatusAttForm').data('bootstrapValidator').resetForm(true);
            });
        }
    };
    var resize = {
        init: function () {
            resize.me();
            $(window).resize(function () {
                resize.me();
            })
        },
        me: function () {
            var winW = $(window).width();
            var winH = $(window).height();
            $(".ibox").width(winW - 20);
            $(".ibox").height(winH - 20);
        }
    };
    $(function () {
        // 返回上级属性状态配置页面
        $("#backToConfig").attr("href", basePath + "rest/statusConfig/statusConfigs");
        // 表格初始化
        var oTable = new TableInit();
        oTable.Init();
        // 新增
        statusAttAddFun.init();
        // 修改
        statusAttEditFun.init();
        // 删除
        statusAttDeleteFun.init();
        // 校验
        validateFun.init();
        resize.init();
    });
</script>
</body>

</html>